package org.jiajie.coffeecodes.concurrent.readwrite;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author jay
 */
public class Counter {
    private final ReadWriteLock rwlock = new ReentrantReadWriteLock();
    private final Lock rlock = rwlock.readLock();
    private final Lock wlock = rwlock.writeLock();
    private int[] counts = new int[10];

    public void inc(int index){
        // 加写锁
        wlock.lock();
        try {
            counts[index] += 1;
        } finally {
            // 释放写锁
            wlock.unlock();
        }
    }

    public int[] get(){
        // 加读锁
        rlock.lock();
        try {
            return Arrays.copyOf(counts, counts.length);
        } finally {
            // 释放读锁
            rlock.unlock();
        }
    }
}
